<template>
  <div class="uploadimg">
    <el-upload
      :action="actionUrl"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :file-list="fileList"
      :http-request="uploadFile"
      list-type="picture">
      <el-button :disabled="disableIinput" size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
    </el-upload>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  /* eslint-disable vue/require-prop-types */
  props: ['dialogType', 'dataimgurl'],
  data() {
    return {
      actionUrl: '',
      disableIinput: false,
      fileList: []
    }
  },
  beforeMount() {
    if (this.dialogType === 1) {
      this.fileList = []
    } else if (this.dialogType === 2) {
      if (this.dataimgurl) {
        const imgurl = this.dataimgurl.split(',')
        for (const val of imgurl) {
          const obj = { url: val }
          this.fileList.push(obj)
        }
      }
    } else if (this.dialogType === 3) {
      this.disableIinput = true
    }
  },
  created() {
    this.fileList = []
    this.initUploadFileurl()
  },
  methods: {
    initUploadFileurl() {
      this.actionUrl = process.env.BASE_API + 'file/uploadImageAndCrtThumbImagesRichEdit'
    },
    uploadFile(content) {
      const file = content.file
      const fd = new FormData()
      fd.append('images', content.file)
      fd.append('resPath', this.resPath)
      const fileSize = file.size < 1048576
      if (!fileSize) {
        this.$message({
          message: '上传图片不能大于 1M',
          type: 'warning'
        })
      } else {
        const loading = this.$loading({
          lock: true,
          text: '保存中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        axios.post(content.action, fd).then(res => {
          loading.close()
          if (res.data.code === 1) {
            const obj = {}
            obj.url = res.data.data[0].maxImageUrl
            this.fileList.push(obj)
            this.$message({
              message: '上传成功',
              type: 'success'
            })
          } else {
            this.$message({
              message: res.data.msg,
              type: 'warning'
            })
          }
        }).catch(res => {
          this.$message({
            type: 'info',
            message: res.message
          })
          loading.close()
        })
      }
    },
    incrementTotal() {
      this.$emit('emitSuccess', this.fileList)
    },
    handleRemove(file, fileList) {
      var _this = this
      this.fileList.forEach(function(item, index) {
        if (file.uid === item.uid) {
          _this.fileList.splice(index, 1)
        }
      })
    },
    handlePreview(file) {
      console.log(file)
    }
  }
}
</script>

<style type="text/scss" lang="scss">
</style>
